$(function() {

	// init date tables
	var tenantListTable = $("#tenant_list").dataTable({
		"deferRender": true,
		"processing" : true,
		"serverSide": true,
		"ajax": {
			url: base_url + "/tenant/pageList",
			type:"post",
			data : function ( d ) {
				var obj = {};
				obj.tenantId = $('#tenantId').val();
				obj.tenantName = $('#tenantName').val();
				obj.validStatus = $('#validStatus').val();
				obj.start = d.start;
				obj.length = d.length;
				return obj;
			}
		},
		"searching": false,
		"ordering": false,
		//"scrollX": true,	// scroll x，close self-adaption
		"columns": [
			{
				"data": 'id',
				"visible" : false,
				"width":'10%'
			},
			{
				"data": 'tenantId',
				"visible" : true,
				"width":'20%'
			},
			{
				"data": 'tenantName',
				"visible" : true,
				"width":'20%'
			},
			{
				"data": 'validStatus',
				"visible" : true,
				"width":'10%',
				"render": function ( data, type, row ) {
					if (data == 'Y') {
						return I18n.tenant_status_valid
					} else {
						return I18n.tenant_status_invalid
					}
				}
			},
			{
				"data": 'accessToken',
				"visible" : true,
				"width":'20%'
			},
			{
				"data": I18n.system_opt ,
				"width":'15%',
				"render": function ( data, type, row ) {
					return function(){
						// html
						tableData['key'+row.id] = row;
						var html = '<p id="'+ row.id +'" >'+
							'<button class="btn btn-warning btn-xs update" type="button">'+ I18n.system_opt_edit +'</button>  '+
							'</p>';

						return html;
					};
				}
			}
		],
		"language" : {
			"sProcessing" : I18n.dataTable_sProcessing ,
			"sLengthMenu" : I18n.dataTable_sLengthMenu ,
			"sZeroRecords" : I18n.dataTable_sZeroRecords ,
			"sInfo" : I18n.dataTable_sInfo ,
			"sInfoEmpty" : I18n.dataTable_sInfoEmpty ,
			"sInfoFiltered" : I18n.dataTable_sInfoFiltered ,
			"sInfoPostFix" : "",
			"sSearch" : I18n.dataTable_sSearch ,
			"sUrl" : "",
			"sEmptyTable" : I18n.dataTable_sEmptyTable ,
			"sLoadingRecords" : I18n.dataTable_sLoadingRecords ,
			"sInfoThousands" : ",",
			"oPaginate" : {
				"sFirst" : I18n.dataTable_sFirst ,
				"sPrevious" : I18n.dataTable_sPrevious ,
				"sNext" : I18n.dataTable_sNext ,
				"sLast" : I18n.dataTable_sLast
			},
			"oAria" : {
				"sSortAscending" : I18n.dataTable_sSortAscending ,
				"sSortDescending" : I18n.dataTable_sSortDescending
			}
		}
	});

	// table data
	var tableData = {};

	// search btn
	$('#searchBtn').on('click', function(){
		tenantListTable.fnDraw();
	});



	jQuery.validator.addMethod("myValid01", function(value, element) {
		var length = value.length;
		var valid = /^[a-z][a-z0-9]*$/;
		return this.optional(element) || valid.test(value);
	}, I18n.user_username_valid );

	// add
	$(".add").click(function(){
		$('#addModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var addModalValidate = $("#addModal .form").validate({
		errorElement : 'span',
		errorClass : 'help-block',
		focusInvalid : true,
		rules : {
			tenantId : {
				required : true,
				rangelength:[2, 20],
				myValid01: true
			},
			tenantName : {
				required : true,
				rangelength:[2, 20]
			},
			adminPassword : {
				required : true,
				rangelength:[4, 20],
				myValid01: true
			},
			accessToken : {
				required : true,
				rangelength:[2, 60]
			}
		},
		messages : {
			tenantId : {
				required : I18n.system_please_input + I18n.tenant_id,
				rangelength: I18n.system_lengh_limit + "[2-20]"
			},
			tenantName : {
				required : I18n.system_please_input + I18n.tenant_name,
				rangelength: I18n.system_lengh_limit + "[2-20]"
			},
			adminPassword : {
				required : I18n.system_please_input + I18n.tenant_admin_password,
				rangelength: I18n.system_lengh_limit + "[4-20]"
			},
			accessToken : {
				required : I18n.system_please_input + I18n.tenant_access_token,
				rangelength: I18n.system_lengh_limit + "[2-60]"
			}
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		success : function(label) {
			label.closest('.form-group').removeClass('has-error');
			label.remove();
		},
		errorPlacement : function(error, element) {
			element.parent('div').append(error);
		},
		submitHandler : function(form) {
			var paramData = {
				"tenantId": $("#addModal .form input[name=tenantId]").val(),
				"tenantName": $("#addModal .form input[name=tenantName]").val(),
				"adminPassword": $("#addModal .form input[name=adminPassword]").val(),
				"validStatus": $("#addModal .form input[name=validStatus]:checked").val(),
				"accessToken": $("#addModal .form input[name=accessToken]").val()
			};

			$.post(base_url + "/tenant/add", paramData, function(data, status) {
				if (data.code == "200") {
					$('#addModal').modal('hide');

					layer.msg( I18n.system_add_suc );
					tenantListTable.fnDraw();
				} else {
					layer.open({
						title: I18n.system_tips ,
						btn: [ I18n.system_ok ],
						content: (data.msg || I18n.system_add_fail),
						icon: '2'
					});
				}
			});
		}
	});
	$("#addModal").on('hide.bs.modal', function () {
		$("#addModal .form")[0].reset();
		addModalValidate.resetForm();
		$("#addModal .form .form-group").removeClass("has-error");
		$(".remote_panel").show();	// remote
	});

	// update
	$("#tenant_list").on('click', '.update',function() {

		var id = $(this).parent('p').attr("id");
		var row = tableData['key'+id];

		// base data
		$("#updateModal .form input[name='id']").val( row.id );
		$("#updateModal .form input[name='tenantId']").val( row.tenantId );
		$("#updateModal .form input[name='tenantName']").val( row.tenantName );
		$("#updateModal .form input[name='adminPassword']").val( '' );
		$("#updateModal .form input[name='validStatus'][value='"+ row.validStatus +"']").click();
		$("#updateModal .form input[name='accessToken']").val( row.accessToken );
		// show
		$('#updateModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var updateModalValidate = $("#updateModal .form").validate({
		rules : {
			tenantName : {
				required : true,
				rangelength:[2, 20]
			},
			adminPassword : {
				required : false,
				rangelength:[4, 20],
				myValid01: true
			},
			accessToken : {
				required : true,
				rangelength:[2, 60]
			}
		},
		messages : {
			tenantName : {
				required : I18n.system_please_input + I18n.tenant_name,
				rangelength: I18n.system_lengh_limit + "[2-20]"
			},
			adminPassword : {
				required : I18n.system_please_input + I18n.tenant_admin_password,
				rangelength: I18n.system_lengh_limit + "[4-20]"
			},
			accessToken : {
				required : I18n.system_please_input + I18n.tenant_access_token,
				rangelength: I18n.system_lengh_limit + "[2-60]"
			}
		},
		errorElement : 'span',
		errorClass : 'help-block',
		focusInvalid : true,
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		success : function(label) {
			label.closest('.form-group').removeClass('has-error');
			label.remove();
		},
		errorPlacement : function(error, element) {
			element.parent('div').append(error);
		},
		submitHandler : function(form) {
			var paramData = {
				"id": $("#updateModal .form input[name=id]").val(),
				"tenantId": $("#updateModal .form input[name=tenantId]").val(),
				"tenantName": $("#updateModal .form input[name=tenantName]").val(),
				"adminPassword": $("#updateModal .form input[name=adminPassword]").val(),
				"accessToken": $("#updateModal .form input[name=accessToken]").val(),
				"validStatus": $("#updateModal .form input[name=validStatus]:checked").val()
			};

			$.post(base_url + "/tenant/update", paramData, function(data, status) {
				if (data.code == "200") {
					$('#updateModal').modal('hide');

					layer.msg( I18n.system_update_suc );
					tenantListTable.fnDraw();
				} else {
					layer.open({
						title: I18n.system_tips ,
						btn: [ I18n.system_ok ],
						content: (data.msg || I18n.system_update_fail),
						icon: '2'
					});
				}
			});
		}
	});
	$("#updateModal").on('hide.bs.modal', function () {
		$("#updateModal .form")[0].reset();
		updateModalValidate.resetForm();
		$("#updateModal .form .form-group").removeClass("has-error");
		$(".remote_panel").show();	// remote
	});

});
